<?php

namespace App\Http\Controllers\Backend\Goods;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Goods\Goods;
use App\Models\Goods\GoodsCate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class GoodsController extends Controller
{
    /**
     * goodsList 商品列表
     * 
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function goodsList(Request $request){
        $type = $request->type ? 1 : 0;
        $lists =$type ?  Goods::getList(false): Goods::getList(true);
        $lists->each(function($item){
           return  $item->thumb = !empty($item->thumb) ? $item->thumb : 'img/goods.jpg';
        })->all();
        return view('backend.goods.goodslist',[
            'lists'=>$lists,
            'type'=>$type,
        ]);
    }

    /**
     * addGoods 添加商品操作
     * 
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function addGoods(Request $request){
        if($request->isMethod('post')){
            $data = $request->all();
            $validator = Goods::validate($request->all());
            if($validator->fails()) {
                return redirect('admin/goodsAdd')
                    ->withErrors($validator)
                    ->withInput();
            }
            $data['sn'] = generateSn(16);
            $data['thumb'] = '';
            $data['picture'] = '';
            if($request->hasFile('picture')) {
                $file = $request->file('picture');
                $name = $file->getClientOriginalName();
                $dirpath = public_path().'/img/uploads/';
                $file->move($dirpath,$name);
                $filePath = 'img/uploads/' . $name;
                $data['picture'] = $filePath;
                $data['thumb'] = $filePath;
            }
            Goods::create($data);
            return redirect('/admin/goodsList');
        }else{
            $gc= new GoodsCate();
            $gclist = $gc->getCategoryInfo();
            return view('backend.goods.goodsadd',['action'=>'add','gclist'=>$gclist]);
        }
    }

    /**
     * updateGoods 编辑商品操作
     * 
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function updateGoods(Request $request){
        if($request->isMethod('post')){
            $all = $request->all();
            if(!$request->hasFile('picture')){
                unset($all['picture']);
            }
            $validator = Goods::validate($all);
            if($validator->fails()) {
                return redirect('admin/goodsUpdate/id/'.$request->id)
                    ->withErrors($validator)
                    ->withInput();
            }
            $save = Goods::find($request->id);
            $save->name = $request->name;
            $save->cate_id = $request->cate_id;
            $save->description = $request->description;
            if($request->hasFile('picture')) {
                $file = $request->file('picture');
                $name = $file->getClientOriginalName();
                $dirpath = public_path().'/img/uploads/';
                $file->move($dirpath,$name);
                $filePath = 'img/uploads/' . $name;
                $save->picture = $filePath;
                $save->thumb = $filePath;
            }
            $save->content = $request->content;
            $save->price = $request->price;
            $save->stock = $request->stock;
            $save->on_sale = $request->on_sale;
            $save->is_recommented = $request->is_recommented;
            $save->save();
            return redirect('/admin/goodsList');
        }else{
            $gc= new GoodsCate();
            $gclist = $gc->getCategoryInfo();
            $item =  Goods::find($request->id);
            return view('backend.goods.goodsadd',['item'=>$item,'action'=>'update','gclist'=>$gclist]);
        }
    }

    /**
     * delGoods 删除产品操作-软删除
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function delGoods(Request $request){
        $count = Goods::withTrashed()->where([['id','=', $request->id],['on_sale','=','1']])->count();
        if($count>0){
            UseAjaxTips('请先下架产品，然后删除！', $request->ajax());
            abort(500,'请先下架产品，然后删除！');
        }
        Goods::where('id', $request->id)->delete();
        UseAjaxTips('删除成功！', $request->ajax(), 500);
        return redirect('/admin/goodsList');
    }

    /**
     * restoreGoods 还原删除的商品
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function restoreGoods(Request $request){
        Goods::withTrashed()->where('id', $request->id)->restore();
        return back();
    }

    /**
     * forceDelGoods 物理删除-数据库中直接删除记录
     * 
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function forceDelGoods(Request $request){
        $count = Goods::withTrashed()->where([['id','=', $request->id],['on_sale','=','1']])->count();
        if($count>0){
            abort(500,'请先下架产品，然后删除！');
        }
        Goods::withTrashed()->where('id', $request->id)->forceDelete();
        $img = DB::table('goods')->where('id', '=', $request->id)->value('picture');
        //删除商品图片
        $dirPath = str_replace('\\', '\/', public_path());
        @unlink($dirPath.'/'.$img);
        return back();
    }
}
